define(['app'], function(app) {
    app.controller('PropertyEditController', ['Config', 'Dialog', 'Context', 'Upload', 'CategoryService',
        function(Config, Dialog, Context, Upload, CategoryService) {
        var self = this;
        self.category = [];
        self.property = {
            id: '',
            name: '',
            categoryId: null,
            price: null,
            buyDate: '',
            description: ''
        };
        self.categoryName = '';
        self.imageName = '';
        self.imageDataUrl = null;

        self.init = function() {
            var data = Context.data;
            if (data != null) {
                self.property.id = data.id;
                self.property.name = data.name;
                self.property.categoryId = data.categoryId;
                self.categoryName = data.categoryName;
                self.property.price = data.price;
                self.property.buyDate = data.buyDate;
                self.property.description = data.description;
            }
            CategoryService.getSubCategory({}).then(function(resp) {
                self.category = resp.data;
            });
        };

        self.upload = function() {
            Dialog.$open().editImage().then(function(data) {
                self.imageName = data.imageName;
                self.imageDataUrl = data.imageDataUrl;
            });
        };

        self.save = function(valid) {
            if (valid) {
                if (self.imageDataUrl == null && (!Context.data || Context.data.imageUrl == null)) {
                    Dialog.$confirm('确定不上传物品图片吗？').then(function() {
                        saveProperty();
                    });
                } else {
                    saveProperty();
                }
            }
        };

        function saveProperty() {
            var data = self.property;
            if (self.imageDataUrl != null) {
                data.file = Upload.dataUrltoBlob(self.imageDataUrl, self.imageName);
            }

            Upload.upload({
                url: Config.baseUrl + '/property/saveProperty',
                timeout: 30000,
                data: data
            }).then(function(resp) {
                if (resp.data.success) {
                    Context.success = true;
                    Context.close();
                }
            }, function (resp) {
                Dialog.$alert(resp.data);
            });
        }
    }]);
});
